import 'dart:convert';

import 'package:shared_preferences/shared_preferences.dart';
import 'package:yqmssa_app/views/landing/apply_request.dart';

final sharedUtils = SharedUtils.instance;

class SharedUtils {
  static final SharedUtils instance = SharedUtils._();

  SharedUtils._();

  late SharedPreferences sharedPrefs;

  Future init() async {
    sharedPrefs = await SharedPreferences.getInstance();
  }

  ///token
  final _tokenKey = "token";

  String get token => sharedPrefs.getString(_tokenKey) ?? "";

  set token(String value) {
    sharedPrefs.setString(_tokenKey, value);
  }

  ///同意协议
  final _agreementKey = "agreement";

  bool get agreement => sharedPrefs.getBool(_agreementKey) ?? false;

  set agreement(bool value) {
    sharedPrefs.setBool(_agreementKey, value);
  }

  ///OaId
  final _oaIdKey = "oaId";

  String get oaId => sharedPrefs.getString(_oaIdKey) ?? "";

  set oaId(String value) {
    sharedPrefs.setString(_oaIdKey, value);
  }

  final _serviceKey = "service";

  CreateApplyDataModel? get service {
    final data = sharedPrefs.getString(_serviceKey);
    if (data == null || data.isEmpty) return null;
    final jsonData = jsonDecode(data);
    return CreateApplyDataModel.fromJson(jsonData);
  }

  set service(CreateApplyDataModel? value) {
    if (value == null) {
      sharedPrefs.remove(_serviceKey);
    } else {
      sharedPrefs.setString(_serviceKey, jsonEncode(value.toJson()));
    }
  }

  final _inviteKey = "invite";

  bool get invite => sharedPrefs.getBool(_inviteKey) ?? false;

  set invite(bool value) {
    sharedPrefs.setBool(_inviteKey, true);
  }

  final _phoneKey = "phone";

  bool get phone => sharedPrefs.getBool(_phoneKey) ?? false;

  set phone(bool value) {
    sharedPrefs.setBool(_phoneKey, value);
  }

  final _weiKey = "weiChat";

  bool get wei => sharedPrefs.getBool(_weiKey) ?? false;

  set wei(bool value) {
    sharedPrefs.setBool(_weiKey, value);
  }

  final _userPhone = "userPhone";

  String get userPhone => sharedPrefs.getString(_userPhone) ?? "";

  set userPhone(String value) {
    sharedPrefs.setString(_userPhone, value);
  }

  final _havePop = "havePop";

  int get havePop => sharedPrefs.getInt(_havePop) ?? 0;

  set havePop(int value) {
    sharedPrefs.setInt(_havePop, value);
  }

  logOut() {
    invite = false;
    userPhone = "";
    service = null;
    token = "";
  }
}
